﻿var zombies = zombies || {};

zombies.ProductDetail = function () {
    var self = this;

    //product info
    self.PId = ko.observable();
    self.Name = ko.observable();
    self.Description = ko.observable();
    self.Score = ko.observable();
    self.ProductImg = ko.observable();
    self.Quantity = ko.observable();
    self.QuantityToOrder = ko.observable();
    //current user info
    self.UserName = ko.observable();

    //collections
    self.Product = ko.observable();
    self.OrderList = ko.observableArray();
    $.cookie.json = true;

    self.doOrder = function (item) {
        self.OrderList.removeAll();

        var dataToSeri = {
            PId: item.PId,
            Name: item.Name,
            Score: item.Score,
            Quantity: item.Quantity,
            ProductImg: item.ProductImg,
            QuantityToOrder: self.QuantityToOrder
        };
        console.log("--x`123--");
        console.log(ko.toJSON(dataToSeri));
        if (dataToSeri.QuantityToOrder() != "" && dataToSeri.QuantityToOrder != null && !isNaN(parseInt(dataToSeri.QuantityToOrder()))) {
            if (dataToSeri.QuantityToOrder() < dataToSeri.Quantity) {
                var flag = 0;
                if (self.UserName() != null) {

                    if ($.cookie(self.UserName()) != null) {
                        var objectNew = $.parseJSON($.cookie(self.UserName()));
                        $.each(objectNew, function (idx, objectNewItem) {
                            console.log('item id : ' + objectNewItem.PId + ', quantity :' + objectNewItem.QuantityToOrder);
                            if (objectNewItem.PId == dataToSeri.PId) {
                                flag = 1;
                                //console.log('go flag = 1');
                                objectNewItem.QuantityToOrder = parseInt(objectNewItem.QuantityToOrder) + parseInt(dataToSeri.QuantityToOrder());
                                self.OrderList.push(objectNewItem);
                            } else {
                                //console.log('go flag = 2');
                                //flag = 0;
                                self.OrderList.push(objectNewItem);
                            }
                        });
                        if (flag == 0) {
                            //console.log('go flag = 0');
                            self.OrderList.push(dataToSeri);
                        }
                    }
                    else {
                        console.log('go flag = 1');
                        self.OrderList.push(dataToSeri);
                    }
                    $.cookie(self.UserName(), ko.toJSON(self.OrderList()), { expires: 1, path: '/' });
                    window.location.replace('http://' + window.location.host + '/Member/ListProduct');
                } else {
                    self.OrderList.push(dataToSeri);
                    $.cookie(self.UserName(), ko.toJSON(self.OrderList()), { expires: 1, path: '/' });
                    window.location.replace('http://' + window.location.host + '/Member/ListProduct');
                }
            } else {
                toastr.error('Quá số lượng trong kho !');
            }
        } else {
            toastr.error('Chưa nhập số lượng !');
        }
    }
};


//load data functions
var loadProducts = function (id) {
    $.ajax({
        url: '/api/MemberProduct/GetProductById/' + id,
        type: 'GET',
        contentType: "application/json; charset=utf-8",
        dataType: "json"
    }).done(function (items) {
        ProductViewModel.Product(new zombies.Product(items));
    }).error(function () {
        toastr.error('error');
    })
};

var loadCurrentUser = function () {
    $.ajax({
        url: '/api/MemberProfile/GetCurrentUser',
        type: 'GET',
        contentType: "application/json; charset=utf-8",
        dataType: "json"
    }).done(function (items) {
        if (items != null) {
            ProductViewModel.UserName(items);
        } else {
            toastr.error('Bạn cần phải login !');
        }
    }).error(function () {
        toastr.error('Lỗi bất thường !');
    })
};

var getUrlVar = function getURLParameter(name) {
    return decodeURI(
     (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search) || [, null])[1]
     );
}

//document ready/ Load view model
var ProductViewModel;
$(document).ready(function () {
    var id = getUrlVar("Id");
    console.log(id);
    ProductViewModel = new zombies.ProductDetail();
    loadProducts(id);
    loadCurrentUser();

    ko.applyBindings(ProductViewModel, document.getElementById("my-container"));
});